// IndexedDB 集成测试工具
import { photoStorage, type PhotoData } from './indexedDB'
import { taskListStorage, type TaskListData } from './taskListDB'
import { studentPhotosStorage, type StudentPhotoData } from './studentPhotosDB'

// 测试结果接口
interface TestResult {
  name: string
  success: boolean
  error?: string
  duration: number
}

// IndexedDB 测试类
export class IndexedDBTester {
  private results: TestResult[] = []

  // 运行所有测试
  async runAllTests(): Promise<TestResult[]> {
    console.log('🧪 开始 IndexedDB 集成测试...')
    
    this.results = []
    
    // 测试照片存储
    await this.testPhotoStorage()
    
    // 测试任务列表存储
    await this.testTaskListStorage()
    
    // 测试学生照片存储
    await this.testStudentPhotosStorage()
    
    // 测试数据持久性
    await this.testDataPersistence()
    
    // 输出测试结果
    this.printResults()
    
    return this.results
  }

  // 测试照片存储
  private async testPhotoStorage() {
    await this.runTest('照片存储测试', async () => {
      // 初始化数据库
      await photoStorage.init()
      
      // 创建测试数据
      const testPhoto: PhotoData = {
        id: 'test-photo-1',
        thumbnail: '-thumbnail',
        fullImage: '-full-image',
        timestamp: Date.now(),
        taskName: '测试任务',
        context: '测试上下文',
        isCreate: true
      }
      
      // 测试保存
      await photoStorage.savePhoto(testPhoto)
      
      // 测试获取
      const savedPhoto = await photoStorage.getPhoto(testPhoto.id)
      if (!savedPhoto || savedPhoto.id !== testPhoto.id) {
        throw new Error('照片保存或获取失败')
      }
      
      // 测试获取所有照片
      const allPhotos = await photoStorage.getPhotos()
      if (!allPhotos.some(photo => photo.id === testPhoto.id)) {
        throw new Error('获取所有照片失败')
      }
      
      // 测试删除
      await photoStorage.deletePhoto(testPhoto.id)
      const deletedPhoto = await photoStorage.getPhoto(testPhoto.id)
      if (deletedPhoto) {
        throw new Error('照片删除失败')
      }
    })
  }

  // 测试任务列表存储
  private async testTaskListStorage() {
    await this.runTest('任务列表存储测试', async () => {
      // 创建测试数据
      const testTask: TaskListData = {
        id: 'test-task-1',
        title: '测试任务',
        description: '这是一个测试任务',
        subject: 'math',
        studentCount: 30,
        startTime: '2024-01-01 09:00',
        endTime: '2024-01-01 11:00',
        status: 'pending',
        statusList: [
          { type: 'create', label: '创建', completed: true },
          { type: 'grade', label: '待批改', completed: false }
        ],
        teacherID: 'teacher-1',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      
      // 测试保存
      await taskListStorage.saveTask(testTask)
      
      // 测试获取
      const savedTask = await taskListStorage.getTask(testTask.id)
      if (!savedTask || savedTask.id !== testTask.id) {
        throw new Error('任务保存或获取失败')
      }
      
      // 测试获取所有任务
      const allTasks = await taskListStorage.getAllTasks()
      if (!allTasks.some(task => task.id === testTask.id)) {
        throw new Error('获取所有任务失败')
      }
      
      // 测试按状态筛选
      const pendingTasks = await taskListStorage.getTasksByStatus('pending')
      if (!pendingTasks.some(task => task.id === testTask.id)) {
        throw new Error('按状态筛选任务失败')
      }
      
      // 测试删除
      await taskListStorage.deleteTask(testTask.id)
      const deletedTask = await taskListStorage.getTask(testTask.id)
      if (deletedTask) {
        throw new Error('任务删除失败')
      }
    })
  }

  // 测试学生照片存储
  private async testStudentPhotosStorage() {
    await this.runTest('学生照片存储测试', async () => {
      // 初始化数据库
      await studentPhotosStorage.init()
      
      // 创建测试数据
      const testStudentPhoto: StudentPhotoData = {
        id: 'test-student-photo-1',
        taskId: 'task-1',
        studentId: 'student-1',
        thumbnail: '-thumbnail',
        fullImage: '-full-image',
        timestamp: Date.now(),
        teacherID: 'teacher-1',
        fileName: 'test-photo.jpg',
        fileSize: '1.2MB',
        description: '测试学生照片',
        status: 'pending'
      }
      
      // 测试保存
      await studentPhotosStorage.savePhoto(testStudentPhoto)
      
      // 测试获取
      const savedPhoto = await studentPhotosStorage.getPhoto(testStudentPhoto.id)
      if (!savedPhoto || savedPhoto.id !== testStudentPhoto.id) {
        throw new Error('学生照片保存或获取失败')
      }
      
      // 测试按任务ID获取
      const taskPhotos = await studentPhotosStorage.getPhotosByTaskId(testStudentPhoto.taskId)
      if (!taskPhotos.some(photo => photo.id === testStudentPhoto.id)) {
        throw new Error('按任务ID获取学生照片失败')
      }
      
      // 测试删除
      await studentPhotosStorage.deletePhoto(testStudentPhoto.id)
      const deletedPhoto = await studentPhotosStorage.getPhoto(testStudentPhoto.id)
      if (deletedPhoto) {
        throw new Error('学生照片删除失败')
      }
    })
  }

  // 测试数据持久性
  private async testDataPersistence() {
    await this.runTest('数据持久性测试', async () => {
      // 创建测试数据
      const testPhoto: PhotoData = {
        id: 'persistence-test-photo',
        thumbnail: '-test',
        fullImage: '-test-full',
        timestamp: Date.now(),
        taskName: '持久性测试'
      }
      
      // 保存数据
      await photoStorage.savePhoto(testPhoto)
      
      // 模拟页面刷新 - 重新初始化存储
      await photoStorage.init()
      
      // 验证数据仍然存在
      const persistedPhoto = await photoStorage.getPhoto(testPhoto.id)
      if (!persistedPhoto || persistedPhoto.id !== testPhoto.id) {
        throw new Error('数据持久性测试失败')
      }
      
      // 清理测试数据
      await photoStorage.deletePhoto(testPhoto.id)
    })
  }

  // 运行单个测试
  private async runTest(name: string, testFn: () => Promise<void>) {
    const startTime = Date.now()
    
    try {
      await testFn()
      const duration = Date.now() - startTime
      
      this.results.push({
        name,
        success: true,
        duration
      })
      
      console.log(`✅ ${name} - 通过 (${duration}ms)`)
    } catch (error) {
      const duration = Date.now() - startTime
      const errorMessage = error instanceof Error ? error.message : String(error)
      
      this.results.push({
        name,
        success: false,
        error: errorMessage,
        duration
      })
      
      console.error(`❌ ${name} - 失败 (${duration}ms):`, errorMessage)
    }
  }

  // 打印测试结果
  private printResults() {
    const totalTests = this.results.length
    const passedTests = this.results.filter(r => r.success).length
    const failedTests = totalTests - passedTests
    const totalDuration = this.results.reduce((sum, r) => sum + r.duration, 0)
    
    console.log('\n📊 IndexedDB 测试结果:')
    console.log(`总测试数: ${totalTests}`)
    console.log(`通过: ${passedTests}`)
    console.log(`失败: ${failedTests}`)
    console.log(`总耗时: ${totalDuration}ms`)
    
    if (failedTests > 0) {
      console.log('\n❌ 失败的测试:')
      this.results
        .filter(r => !r.success)
        .forEach(r => console.log(`  - ${r.name}: ${r.error}`))
    }
  }

  // 获取测试结果
  getResults(): TestResult[] {
    return [...this.results]
  }

  // 检查所有测试是否通过
  allTestsPassed(): boolean {
    return this.results.every(r => r.success)
  }
}

// 创建测试实例
export const indexedDBTester = new IndexedDBTester()

// 便捷的测试运行函数
export async function runIndexedDBTests(): Promise<boolean> {
  const results = await indexedDBTester.runAllTests()
  return indexedDBTester.allTestsPassed()
}
